//
//  RSNetTool.swift
//  RSWeibo
//
//  Created by Macx on 16/8/9.
//  Copyright © 2016年 Macx. All rights reserved.
//

import UIKit
import AFNetworking

// 定义一个枚举, 用来区分 get 或 post 请求
enum RequestType: Int {

    case GET = 0
    case POST = 1
}



// 声明一个网络工具类
class RSNetTool: AFHTTPSessionManager {
    
    // 创建全局的单例, swift 中创建单例的关键字 static let
    static let sharedTool: RSNetTool = {
        
        let tools = RSNetTool()
        
        // 增加可接受的类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
            
        return tools
        
        }()
    
    //  网络请求的方法
    func requestNet(requestType: RequestType, urlStr: String, parameter: AnyObject, callBackClosur:(reseponse: AnyObject?, error: NSError?)->() ) -> () {
        
        // 根据不同的请求类型确定调用相对应的请求方法
        if requestType == .GET {
         
            GET(urlStr, parameters: parameter, success: { (_, response) -> Void in
                
                // 请求成功, 则调用闭包, 把error的返回值设为nil
                callBackClosur(reseponse: response,error: nil)
                
                }, failure: { (_, error) -> Void in
                    // 请求失败, 则调用闭包, 把response的返回值设为nil
                    callBackClosur(reseponse: nil,error: error)
                    
            })
            
        }else if requestType == .POST{
        
            POST(urlStr, parameters: parameter, success: { (_, response) -> Void in
                // 请求成功, 则调用闭包, 把error的返回值设为nil
                callBackClosur(reseponse: response,error: nil)
                
                }, failure: { (_, error) -> Void in
                    
                    // 请求失败, 则调用闭包, 把response的返回值设为nil
                    callBackClosur(reseponse: nil,error: error)
            })
        }
        
    }
    
    // 封装上传图片的接口
    func requestUpload(url: String, params: AnyObject?, imageData: NSData, name: String, callBack: (reseponse: AnyObject?, error: NSError?)->()){
    
        POST(url, parameters: params, constructingBodyWithBlock: { (formData)->Void in
            //  data 图片对应的二进制数据
            //  name 服务端需要参数
            //  fileName 图片对应名字,一般服务不会使用,因为服务端会直接根据你上传的图片随机产生一个唯一的图片名字
            //  mimeType 资源类型
            //  不确定参数类型 可以这个 octet-stream 类型, 二进制流
            formData.appendPartWithFileData(imageData, name: name, fileName: "test", mimeType: "application/octet-stream")
            }, success: { (_, response) in
                callBack(reseponse: response, error: nil)
            }) { (_, error) in
               callBack(reseponse: nil, error: error)
        }
        
    }

}


// 请求获取 OAuth2/access token的窗口方法
extension RSNetTool{

    func requestAccess_tokenWithCode(code: String, callBack:(reseponse: AnyObject?, error: NSError?)->()){
        
        // 窗口地址
        let urlstr = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let parameter: [String : AnyObject] = [
            "client_id" : appKey,
            "client_secret" : appSecrect,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : callBakeUrl
        ]

    
        // 使用POST 方法
        // 网络工具
        requestNet(.POST, urlStr: urlstr, parameter: parameter, callBackClosur: callBack)
        
    }
    
    
    // 通过access_token和 uid 获取用户信息
    
}

// 请求用户信息
// Oauth2/get token info
extension RSNetTool{
    
    func getTokendInfoWithAccess_Token(access_Token: String, callBack:(reseponse: AnyObject?, error: NSError?)->()){
    
        // 窗口地址
        let urlstr = "https://api.weibo.com/oauth2/get_token_info"
        // 请求参数
        let parameter: [String : AnyObject] = [
            "access_token" : access_Token,
           
        ]

        requestNet(.POST, urlStr: urlstr, parameter: parameter, callBackClosur: callBack)
        
    }
    

    
}

// 通过access_token和uid获取用户信息users/show

extension RSNetTool{
    
    func getUser_show(userAccountModel: RSUserAccountModel, access_token: String, callBack:(reseponse: AnyObject?, error: NSError?)->()) {
        // 窗口地址
        let urlstr = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let parameter: [String : AnyObject] = [
            "access_token" : access_token,
            "uid" : "\(userAccountModel.uid)"
            
        ]
        requestNet(.GET, urlStr: urlstr, parameter: parameter, callBackClosur: callBack)

    }
}


// statuses/friends_timeline

// 获取当前登录用户及其所关注（授权）用户的最新微博
// 下拉刷新数据, 需要多加一个参数 max_id
extension RSNetTool{

    func getstatuses_friends_timeline(access_token: String, maxId: Int64, sinceId: Int64, callBack:(reseponse: AnyObject?, error: NSError?)->()){
    
        // 窗口地址
        let urlstr = "https://api.weibo.com/2/statuses/friends_timeline.json"
        // 请求参数, Int64不属于对象类, 所以要包装成对象类
        let parameter: [String : AnyObject] = [
            "access_token" : access_token,
            "max_id" : "\(maxId)",
            "since_id": "\(sinceId)"
        ]
        
//        print("&&&&&&&&&&&&&&&", sinceId)
//
//        let path = urlstr + "?access_token=" + access_token
//        print("88888",path)
        
        requestNet(.GET, urlStr: urlstr, parameter: parameter, callBackClosur: callBack)

    }
}


// 上传发表微博的接口
extension RSNetTool{
    
    // 有文字有图片的接口
    func sendstatusAndimages(access_token: String, status: String, image: UIImage, callBack:(reseponse: AnyObject?, error: NSError?)->()){
    
        // 窗口地址
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        // 请求参数, Int64不属于对象类, 所以要包装成对象类
        let parameter: [String : AnyObject] = [
            "access_token" : access_token,
            "status" : status,
            
            ]
        // 图片转换成二进制数据
        //法一: 转换后的二进制数据很大
//        let imgData = UIImagePNGRepresentation(image)
        // 法二, 转换后的二进制数据比较小
        let imgData = UIImageJPEGRepresentation(image, 0.5)
        
        // 调动接口, 
        requestUpload(urlStr, params: parameter, imageData: imgData!, name: "pic", callBack:callBack )
        

        
    }

    // 只有文字的接口
    func sendStatuses(access_token: String, status: String, callBack:(reseponse: AnyObject?, error: NSError?)->()){
    
        // 窗口地址
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        
        // 请求参数, Int64不属于对象类, 所以要包装成对象类
        let parameter: [String : AnyObject] = [
            "access_token" : access_token,
            "status" : status,
            
        ]
        
        requestNet(.POST, urlStr: urlStr, parameter: parameter, callBackClosur: callBack)
        

    }
}



































